package com.monkeyboy.service;

import com.alibaba.fastjson.JSON;
import com.monkeyboy.utils.HtmlParseUtil;
import com.monkeyboy.modul.HtmlContent;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Gavin
 * @date 2020.09.01 11:14
 */
@Service
public class SearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //1.解析数据放入es索引库中
    public Boolean parseJDContent(String keyWords) throws Exception {
        List<HtmlContent> dataList = HtmlParseUtil.JD_Search(keyWords);
        //把爬取出来的数据放入到es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < dataList.size(); i++) {
            System.out.println(dataList.get(i));
            bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(dataList.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    //2.解析爱回收数据放入es索引库中
    public Boolean parseAihuishouContent() throws Exception {
        List<HtmlContent> dataList = HtmlParseUtil.scrapAihuishouData();
        //把爬取出来的数据放入到es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < dataList.size(); i++) {
            System.out.println(dataList.get(i));
            bulkRequest.add(new IndexRequest("aihuishou_goods").source(JSON.toJSONString(dataList.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    /**
     * 搜索
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws Exception {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //精准查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        //模糊匹配
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword);
        sourceBuilder.query(matchQuery);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//不需要多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果（没有高亮的读取步骤）
        ArrayList<Map<String, Object>> resData = new ArrayList<>();
        for (SearchHit pre : search.getHits().getHits()) {
            resData.add(pre.getSourceAsMap());
        }

        return resData;
    }

    /**
     * 搜索+高亮显示
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> searchPageHighlight(String keyword, int pageNo, int pageSize) throws Exception {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //精准查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        //模糊匹配
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword);
        sourceBuilder.query(matchQuery);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//不需要多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //高亮读取步骤
        ArrayList<Map<String, Object>> resData = new ArrayList<>();
        for (SearchHit pre : search.getHits().getHits()) {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = pre.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = pre.getSourceAsMap();
            //解析高亮字段，将原来的字段换为我们高亮的字段即可
            if (title != null) {
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text pre1 : fragments) {
                    n_title += pre1;
                }
                sourceAsMap.put("title", n_title);//替换原来的title字段
            }
            resData.add(pre.getSourceAsMap());
        }
        return resData;
    }
}
